﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

using CloudSoft.Extensions;

namespace ERPStore.Web.NewsLetters.MessageReaders
{
	public class NewsLetterBodyCreationRequestMessageReader : Ariane.MessageReaderBase<ERPStore.NewsLetters.Models.PendingItem>
	{
		public NewsLetterBodyCreationRequestMessageReader(ERPStore.NewsLetters.Services.NewsLettersService newsLetterService
			, ERPStore.Services.IEmailerService emailerService
			, ERPStore.Web.Services.IEmailTemplateService emailTemplateService
			, ERPStore.Services.IServiceBus bus
			)
		{
			this.NewsLetterService = newsLetterService;
			this.EmailerService = emailerService;
			this.EmailTemplateService = emailTemplateService;
			this.Bus = bus;
		}

		protected ERPStore.NewsLetters.Services.NewsLettersService NewsLetterService { get; private set; }
		protected ERPStore.Services.IEmailerService EmailerService { get; private set; }
		protected ERPStore.Web.Services.IEmailTemplateService EmailTemplateService { get; private set; }
		protected ERPStore.Services.IServiceBus Bus { get; private set; }

		public override void ProcessMessage(ERPStore.NewsLetters.Models.PendingItem pendingItem)
		{
			var campaign = NewsLetterService.GetCampaignById(pendingItem.CampaignId);
			var newsLetter = NewsLetterService.GetNewsLetterById(campaign.NewsLetterId);

			var recipient = NewsLetterService.GetEmailRecipientById(pendingItem.EmailRecipientId);
			if (recipient.IsBlackListed)
			{
				return;
			}

			var model = new ERPStore.NewsLetters.Models.CustomerNewsLetter()
			{
				Campaign = campaign,
				NewsLetter = newsLetter,
				ShowEmailLink = true,
				ShowUnsubscribeLink = true,
				Recipient = recipient,
			};

			var emailView = EmailTemplateService.CreateEmailView(newsLetter.ContentViewName, model);
			var template = EmailTemplateService.CreateEmailMessage(emailView);

			template.From = new ERPStore.Models.MailAddress() { Address = campaign.ReplyToEmail, DisplayName = campaign.ReplyToEmailName };
			template.Recipients.Add(new ERPStore.Models.MailAddress() { Address = recipient.Email, DisplayName = recipient.FullName, SendingType = ERPStore.Models.EmailSendingType.To });

			template.Headers.Add(new ERPStore.Models.MailMessageHeader() { Name = "X-Mailer", Value = "ERPStore.NewsLetters" });
			template.Headers.Add(new ERPStore.Models.MailMessageHeader() { Name = "X-NLRID", Value = recipient.Id.ToString() });
			template.Headers.Add(new ERPStore.Models.MailMessageHeader() { Name = "X-NLCID", Value = campaign.Id.ToString() });

			pendingItem.MailMessage = template;

			Bus.Send(ERPStore.NewsLetters.Queues.QUEUE_SEND, pendingItem);
		}

		private void AttachInternalImage(System.Net.Mail.MailMessage mailMessage)
		{
			string imagePattern = @"(src=[\""|']{0,1}(?<src>\w:\\[^\""|\s]*)[[\""|']{0,1}|\s*]|src=[\""|']{0,1}(?<prefix>file:///)(?<src>\w:/[^\""|\s]*)[[\""|']{0,1}|\s*])";
			imagePattern = @"src=[\""|']{0,1}/newsletters(?<src>[^\""|\s]*)[[\""|']{0,1}|\s*]";
			var exp = new System.Text.RegularExpressions.Regex(imagePattern, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			System.Text.RegularExpressions.Match m;
			var imageList = new List<LinkedResource>();

			var virtualFilePath = ERPStore.NewsLetters.Configuration.ConfigurationSettings.AppSettings["virtualFilePath"];
			var physicalPath = ERPStore.GlobalConfiguration.Configuration.Settings.PhysicalPath;
			physicalPath = System.IO.Path.Combine(physicalPath, virtualFilePath.Replace("~/", "").Replace("/", @"\"));

			for (m = exp.Match(mailMessage.Body); m.Success; m = m.NextMatch())
			{
				if (m.Value.Length == 0)
				{
					continue;
				}
				var originalsrc = m.Groups["src"].Value;
				if (originalsrc.IsNullOrEmpty())
				{
					continue;
				}
				// originalsrc = originalsrc.Replace("newsletters", "");
				var src = System.IO.Path.Combine(physicalPath, originalsrc.Replace('/', '\\').TrimStart('\\'));
				var ext = System.IO.Path.GetExtension(src).Replace(".", "").ToLower();
				var mimeType = ERPStore.Extensions.MimeExtensions.MIMETypeDictionary.FirstOrDefault(i => i.Key.Equals(ext));
				var img = new LinkedResource(src, mimeType.Value);
				var id = Guid.NewGuid().ToString().Substring(0, 8) + "." + ext;
				img.ContentId = id;
				imageList.Add(img);
				mailMessage.Body = mailMessage.Body.Replace("/newsletters" + originalsrc, string.Format("cid:{0}", id));
			}

			var htmlView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, null, "text/html");
			foreach (var lr in imageList)
			{
				htmlView.LinkedResources.Add(lr);
			}
			htmlView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;

			mailMessage.AlternateViews.Add(htmlView);
		}

	}
}
